package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.ICategoryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private ICategoryService categoryService;

    /**
     * 新增分类
     * @param category
     * @return
     */
    @PostMapping
    public R<String> addCategory(@RequestBody Category category){
        boolean add = categoryService.save(category);
        if(add){
            return R.success("新增菜品成功");
        }
        return R.error("新增失败");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(Integer page,Integer pageSize){
        //新建分页查询器
        Page<Category> pageInfo = new Page<>(page,pageSize);
        //条件查询
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.orderByDesc(Category::getSort);
        categoryService.page(pageInfo,qw);
        return R.success(pageInfo);
    }

    /**
     * 根据id删除分类
     * @param id
     * @return
     */
    @DeleteMapping
    public R<String> deleteById(Long id){
        //boolean deleteInfo = categoryService.removeById(id);
        categoryService.remove(id);

        return R.success("分类信息删除成功");

    }

    /**
     * 删除分类
     * @param category
     * @return
     */
    @PutMapping
    public R<String> updateCategory(@RequestBody Category category){
         categoryService.updateById(category);
         return R.success("修改分类数据成功");
    }

    /**
     * 菜品在页面显示
     * @param
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> select(Category category){
        //分类条件
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.eq(category.getType()!=null,Category::getType,category.getType());
        qw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> list = categoryService.list(qw);

        return R.success(list);

    }
    /*@GetMapping("/list")
    public R<List<Category>> select(Integer type){
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(type!=null,Category::getType,type);
        queryWrapper.orderByAsc(Category::getSort);

        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }*/
}
